﻿namespace LinqToSqlQueryVisualizer
{
    using System;
    using System.Globalization;

    internal static class Utils
    {
        /// <summary>
        /// Translates the sql query text (which contains parameter names)
        /// and the information about the parameters (SqlType and value as given by .ToString())
        /// into one sql string (that contains text representations of the values).
        /// Executing this string should be the same as executing the original query except in 
        /// corner cases (e.g. a string contains a parameter name, a decimal is given with too high precision).
        /// </summary>
        /// <param name="qt">Query text and information about the parameters.</param>
        /// <returns>The sql string to execute.</returns>
        internal static string GetQueryTextWithParams(SqlQueryText qt)
        {
            var s = qt.Text;
            for (var i = qt.Params.Length - 1; i >= 0; i--)
            {
                var param = qt.Params[i];
                string val;
                switch (param.SqlType)
                {
                    case "String":
                    case "Guid":
                    case "DateTime":
                        val = QuoteString(param.Value);
                        break;

                    case "Boolean":
                        switch (param.Value)
                        {
                            case "True":
                                val = "1";
                                break;
                            case "False":
                                val = "0";
                                break;
                            default:
                                throw new ArgumentException("Boolean value other than True or False");
                        }

                        break;

                    case "Time":
                        var ts = TimeSpan.Parse(param.Value);
                        val = ts.Ticks.ToString(CultureInfo.CurrentUICulture);
                        break;

                    default:
                        val = param.Value;
                        break;
                }

                s = s.Replace(param.Name, val);
            }

            return s;
        }

        internal static string QuoteString(string raw)
        {
            return "'" + raw.Replace("'", "''") + "'";
        }
    }
}